package com.zz.common.tunnel;

import com.zz.common.utils.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 隧道启动助手
 */
@Slf4j
public class TunnelHelper {


    private static List<Tunnel> tunnelCaches;

    /** 隧道运行状态 **/
    private static volatile boolean runStatus = true;

    public static void start(List<Tunnel> tunnelList) {
        tunnelCaches = tunnelList;

        // 启动
        startTunnel();
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                synchronized (TunnelHelper.class) {
                    stopTunnel();
                    runStatus = false;
                    TunnelHelper.class.notify();
                }
            }
        });

        synchronized (TunnelHelper.class) {
            while (runStatus) {
                try {
                    TunnelHelper.class.wait();
                    stopCallback();
                } catch (InterruptedException e) {
                    log.error("TunnelHelper stopCallback error", e);
                }
            }
        }
    }

    public static void stop() {
        stopTunnel();
        System.exit(0);
    }


    public static void startTunnel() {
        if (ObjectUtil.isEmpty(tunnelCaches)) {
            log.info("start error tunnelCaches is empty...");
            return;
        }
        tunnelCaches.forEach(Tunnel::start);
    }

    public static void stopTunnel() {
        if (ObjectUtil.isEmpty(tunnelCaches)) {
            log.info("stop error tunnelCaches is empty");
            return;
        }
        tunnelCaches.forEach(Tunnel::stop);
    }

    /**
     * 隧道停止后回调
     */
    public static void stopCallback() {

    }
}
